﻿function ERMgmt() {
    this.ERTabStrip = null;
    this.SearchGrid = null;
    this.TitleCtrl = null;
    this.VesselCtrl = null;
    this.FirstReportCtrl = null;
    this.IncedentTypeCtrl = null;
    this.CloseCtrl = null;
    this.CloseCommentCtrl = null;
    this.FileUploader = null;
    this.FeedbackFilter = null;
    this.FeedbackGrid = null;

    this.GetFilesCallBack = null;

    this.GetActiveTabIndex = function () {
        if (this.ERTabStrip != null) {
            return this.ERTabStrip.get_selectedTab().get_index();
        }
        else {
            throw 'Cannot load RadTabStrip.';
        }
    }

    this.SelectTabByName = function (pName) {
        if (this.ERTabStrip != null) {
            return this.ERTabStrip.findTabByText(pName).set_selected(true);
        }
        else {
            throw 'Cannot load vessel Tabs.';
        }
    }

    this.SelectTabByIndex = function (pTabIdx) {
        if (this.ERTabStrip != null) {
            this.ERTabStrip.get_tabs().getTab(pTabIdx).select();
        }
        else {
            throw 'Cannot load vessel Tabs.';
        }
    }

    this.LoadVessels = function () {
        Landscape.AdministrativeActions.GetVesselListByName('', 0, -1, function (result, e) {
            var items = e.VesselCtrl.get_items();
            e.VesselCtrl.trackChanges();

            var comboItem = new Telerik.Web.UI.RadComboBoxItem();
            comboItem.set_text('-Select-');
            comboItem.set_value('00000000-0000-0000-0000-000000000000');
            items.add(comboItem);

            for (var idx = 0; idx < result.length; idx++) {
                comboItem = new Telerik.Web.UI.RadComboBoxItem();
                comboItem.set_text(result[idx].Name);
                comboItem.set_value(result[idx].ID);

                items.add(comboItem);
            }

            items.getItem(0).select();

            e.VesselCtrl.commitChanges();
        }, function (result, e) { N_NotifyMessage('Error !!!', result.get_message(), 2); }, this);
    }

    this.SaveIncident = function () {
        if (this.CheckCtrls()) {
            var currentERObject = MASTER_GetCurrentBusinessObject();
            if (this.GetActiveTabIndex() == 1) {
                if (currentERObject == null) {
                    //New Object
                    currentERObject = new Landscape.EmergencyIncident();
                    currentERObject.ID = '00000000-0000-0000-0000-000000000000';
                    currentERObject.CreatedBy = MASTER_GetCurrentUserCode();
                    currentERObject.CreatedDate = new Date();
                }
                else {
                    if (currentERObject.IsClosed) {
                        N_NotifyMessage('Incident Closed !!!', 'The selected incident is already closed. Further updates cannot be saved.', 2);
                        return;
                    }
                }
                currentERObject.UpdatedBy = MASTER_GetCurrentUserCode();
                currentERObject.UpdatedDate = new Date();

                currentERObject.Title = this.TitleCtrl.get_value();
                currentERObject.FirstIncidentReportTime = this.FirstReportCtrl.get_selectedDate(); //new Date(this.FirstReportCtrl.get_selectedDate().toGMTString());

                currentERObject.IsIncident = (this.IncedentTypeCtrl.value == 'true' ? true : false);

                currentERObject.CloseComment = this.CloseCommentCtrl.value;
                currentERObject.IsDeleted = false;
                currentERObject.VesselCode = this.VesselCtrl.get_value();

                Landscape.EmergencyActions.SaveEmergencyIncident(currentERObject, function (result, e) {
                    currentERObject.ID = result;
                    MASTER_StoreCurrentBusinessObject(currentERObject);

                    if (!currentERObject.IsClosed)
                        window.setInterval(showTimer, 1000);

                    N_NotifyMessage('Saved !!!', 'Incident details saved, please proceed to emergency response tab.', 1);
                }, function (result, e) { N_NotifyMessage('Error !!!', result.get_message(), 2); }, currentERObject);
            }
            else {
                //Files upload
                if (this.GetActiveTabIndex() == 4) {
                    var fileList = this.FileUploader.GetUploadedFiles(); //CommitFiles
                    Landscape.EmergencyActions.CommitFiles(fileList, MASTER_GetCurrentBusinessObject().ID, function (result, e) {
                        N_NotifyMessage('Uploaded !!!', 'Files uploaded successfully.', 1);
                        e.FileUploader.LoadFiles(MASTER_GetCurrentBusinessObject().ID);
                    }, function (result, e) { N_NotifyMessage('Error !!!', result.get_message(), 2); }, this);
                }
            }
        }
    }

    this.CloseIncident = function (closeComments) {
        if (this.CheckCtrls()) {
            var currentERObject = MASTER_GetCurrentBusinessObject();
            if (currentERObject == null) {
                //New Object
                currentERObject = new Landscape.EmergencyIncident();
                currentERObject.ID = '00000000-0000-0000-0000-000000000000';
                currentERObject.CreatedBy = MASTER_GetCurrentUserCode();
                currentERObject.CreatedDate = new Date();
            }
            currentERObject.UpdatedBy = MASTER_GetCurrentUserCode();
            currentERObject.UpdatedDate = new Date();

            currentERObject.Title = this.TitleCtrl.get_value();
            currentERObject.FirstIncidentReportTime = this.FirstReportCtrl.get_selectedDate();
            currentERObject.IsIncident = (this.IncedentTypeCtrl.value == 'true' ? true : false);
            currentERObject.IsClosed = this.CloseCtrl.checked;
            if (this.CloseCtrl.checked) {
                currentERObject.ClosedDate = new Date();
                currentERObject.ClosedBy = MASTER_GetCurrentUserCode();
                currentERObject.CloseComment = closeComments;
            }            
            currentERObject.IsDeleted = false;
            currentERObject.VesselCode = this.VesselCtrl.get_value();

            Landscape.EmergencyActions.SaveEmergencyIncident(currentERObject, function (result, e) {
                currentERObject.ID = result;
                MASTER_StoreCurrentBusinessObject(currentERObject);

                if (!currentERObject.IsClosed)
                    window.setInterval(showTimer, 1000);

                N_NotifyMessage('Incident Closed !!!', 'The incident is closed successfully.', 1);
            }, function (result, e) { N_NotifyMessage('Error !!!', result.get_message(), 2); }, currentERObject);
        }
    }

    this.SearchIncidenets = function () {
        if (this.CheckCtrls(false)) {
            var pageSize = this.SearchGrid.get_masterTableView().get_pageSize();
            var pageNo = this.SearchGrid.get_masterTableView().get_currentPageIndex();

            Landscape.EmergencyActions.GetEmergencyIncidentsByTitle('', pageNo, pageSize, function (result, e) {
                e.get_masterTableView().set_dataSource(result);
                e.get_masterTableView().dataBind();
            }, function (result, e) { N_NotifyMessage('Error !!!', result.get_message(), 2); }, this.SearchGrid);
        }
    }

    this.LoadIncidenetFeedback = function () {
        if (this.CheckCtrls(false)) {
            var pageSize = this.FeedbackGrid.get_masterTableView().get_pageSize();
            var pageNo = this.FeedbackGrid.get_masterTableView().get_currentPageIndex();

            Landscape.EmergencyActions.GetFeedbackList(MASTER_GetCurrentBusinessObject().ID, this.FeedbackFilter.get_text(), pageNo, pageSize, function (result, e) {
                e.get_masterTableView().set_dataSource(result);
                e.get_masterTableView().dataBind();
            }, function (result, e) { N_NotifyMessage('Error !!!', result.get_message(), 2); }, this.FeedbackGrid);
        }
    }

    this.LoadIncidentDetails = function (pIncID) {
        $.connection.hub.stop();
        Landscape.EmergencyActions.GetEmergencyIncidentDetailsByID(pIncID, function (result, e) {
            e.TitleCtrl.set_value(result.Title);
            e.FirstReportCtrl.set_selectedDate(result.FirstIncidentReportTime);

            e.CloseCtrl.innerHTML = (result.IsClosed ? 'Yes' : 'No');            
            e.VesselCtrl.set_value(result.VesselCode);
            e.VesselCtrl.findItemByValue(result.VesselCode).select();

            if (result.IsIncident) {
                e.IncedentTypeCtrl.rows[0].cells[0].firstChild.checked = true;
            }
            else {
                e.IncedentTypeCtrl.rows[0].cells[1].firstChild.checked = true;
            }

            MASTER_StoreCurrentBusinessObject(result);
            e.FileUploader.LoadFiles(MASTER_GetCurrentBusinessObject().ID);
            e.FileUploader.ClearFilesToUpload();

            Landscape.EmergencyActions.GetFeedbackList(MASTER_GetCurrentBusinessObject().ID, 'All', 0, 10, function (result, e) {
                e.FeedbackGrid.get_masterTableView().set_dataSource(result);
                e.FeedbackGrid.get_masterTableView().dataBind();
            }, function (result, e) { N_NotifyMessage('Error !!!', result.get_message(), 2); }, e);

            if (!e.IsClosed) {
                window.setInterval(showTimer, 1000);

                //Initialize the scribe singnals
                $.connection.hub.start().done(InitHubSignal);
            }
        }, function (result, e) { N_NotifyMessage('Error !!!', result.get_message(), 2); }, this);

        this.SelectTabByIndex(1);
    }

    function InitHubSignal() {
        initScribeHubSignal();
        initChatHubSignal();
    }

    this.SaveStatusUpdate = function (pStatusItemCode, pMessage, pShortName) {
        if (pMessage.trim() != '') {
            var currentERObject = MASTER_GetCurrentBusinessObject();
            Landscape.EmergencyActions.SaveStatusUpdate(pStatusItemCode, currentERObject.ID, pMessage, MASTER_GetCurrentUserCode(), function (result, e) {
                var bizObject = MASTER_GetCurrentBusinessObject();
                var sItem = { 'IncidentCode': bizObject.ID,
                    'ItemTimeStamp': new Date(),
                    'Message': e,
                    'CreatedBy': MASTER_GetCurrentUserCode(),
                    'MessageType': 'STATUS_UPDATE',
                    'ShortItemName': pShortName.toUpperCase()
                };
                $.connection.ScribeMini.server.addToScribeLog(sItem).done(function () { });
            }, function (result, e) { N_NotifyMessage('Error !!!', result.get_message(), 2); }, pMessage);
        }
    }

    this.CheckCtrls = function (pForSave) {
        var hasError = false;
        var errorMsg = '';

        if (this.ERTabStrip == null) {
            hasError = true;
            errorMsg += 'Unable to load ER management tabs.';
        }

        if (this.SearchGrid == null) {
            hasError = true;
            errorMsg += 'Unable to load search grid.';
        }

        if (this.TitleCtrl == null) {
            hasError = true;
            errorMsg += 'Unable to load title control.';
        }
        else {
            if ((this.TitleCtrl.get_value().length <= 0 || this.TitleCtrl.get_value().length > 256) && pForSave) {
                hasError = true;
                errorMsg += 'The no. of charectors in the title should be between 1 - 256.';
            }
        }

        if (this.VesselCtrl == null) {
            hasError = true;
            errorMsg += 'Unable to load vessle combo box.';
        }
        else {
            if ((this.VesselCtrl.get_value() == '-Select-') && pForSave) {
                hasError = true;
                errorMsg += 'Select the vessel.';
            }
        }

        if (this.FirstReportCtrl == null) {
            hasError = true;
            errorMsg += 'Unable to load first report time control.';
        }
        else {
            if ((this.FirstReportCtrl.get_selectedDate() == null) && pForSave) {
                hasError = true;
                errorMsg += 'Select the time of first report.';
            }
        }

        if (this.IncedentTypeCtrl == null) {
            hasError = true;
            errorMsg += 'Unable to load incident type control.';
        }
        else {
            if ((this.IncedentTypeCtrl.value != 'true' || this.IncedentTypeCtrl.value != 'false') && pForSave) {
                hasError = true;
                errorMsg += 'Select the incident type.';
            }
        }

        if (this.CloseCtrl == null) {
            hasError = true;
            errorMsg += 'Unable to load close control.';
        }

        if (this.CloseCommentCtrl == null) {
            hasError = true;
            errorMsg += 'Unable to load close comment control.';
        }

        if (this.FeedbackFilter == null) {
            hasError = true;
            errorMsg += 'Unable to load feedback filter combo box control.';
        }

        if (this.FeedbackGrid == null) {
            hasError = true;
            errorMsg += 'Unable to load feedback grid control.';
        }

        if (hasError) {
            throw errorMsg;
        }

        return !hasError;
    }

    this.ClearCtrls = function () {
        this.TitleCtrl.set_value('');
        this.VesselCtrl.get_items().getItem(0).select();
        this.FirstReportCtrl.set_selectedDate(new Date());
        this.CloseCtrl.checked = false;
        this.FileUploader.Reset();
        this.FeedbackGrid.get_masterTableView().set_dataSource(new Array());
        this.FeedbackGrid.get_masterTableView().dataBind();
    } 
}